package com.stone.framework.gateway.filter;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * @see {GatewayConfig#corsFilter}
 * @author ybliu
 * @date 2020/07/20
 */
// @Component
@Deprecated
public class ResponseHeaderGlobalFilter implements GlobalFilter, Ordered {

    @Value("${stone.res-header.skip-paths}")
    private List<String> skipPaths;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        Optional<String> optional =
            skipPaths.stream().filter(skipPath -> path.substring(path.indexOf("/", 1)).startsWith(skipPath)).findAny();
        if (optional.isPresent()) {
            return chain.filter(exchange);
        }

        HttpHeaders headers = new HttpHeaders();
        if (HttpMethod.OPTIONS.equals(exchange.getRequest().getMethod())) {
            headers.setAccessControlAllowOrigin(exchange.getRequest().getHeaders().getOrigin());
            headers.setAccessControlAllowHeaders(Arrays.asList(HttpHeaders.CONTENT_TYPE, HttpHeaders.AUTHORIZATION));
            headers.setAccessControlAllowMethods(Arrays.asList(HttpMethod.GET, HttpMethod.POST));
            headers.setAccessControlMaxAge(60 * 5);
            exchange.getResponse().getHeaders().addAll(headers);
            exchange.getResponse().setStatusCode(HttpStatus.OK);
            return Mono.empty();
        }
        headers.setAccessControlAllowCredentials(true);
        exchange.getResponse().getHeaders().addAll(headers);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }

}
